//
//  MessageViewController.m
//  SouthChina
//
//  Created by Mr.Y on 14/11/21.
//  Copyright (c) 2014年 科创. All rights reserved.
//

#import "MessageViewController.h"
#import "MessageSendCell.h"
#import "MessageReceiveCell.h"
#import "ContactDao.h"
#import "MessageSessionDao.h"
#import "SingleNewsCell.h"
#import "MultipleNewsCell.h"
#import "UrlCell.h"
#import "SignCell.h"
#import "PublicInforDetailViewController.h"
#import "ContactDetailController.h"
#import "GroupDetailController.h"
#import "TakePhotoController.h"
#import "StorageEngine.h"
#import "MessageListViewController.h"
#import "ImageShowerController.h"
#import "KeyWordDao.h"
#import "GroupInfoViewController.h"






@interface MessageViewController ()<UITextViewDelegate,UITableViewDataSource,UITableViewDelegate>
{
    NSArray *msgList;
    NSString *dbrecordDBPKID;
    NSString *dbrecordID;
    MessageAudioRecoder *recoder;
    
    EGORefreshTableHeaderView *_refreshHeaderView;
    
    int tableHeight;
    
    NSMutableDictionary *heightForCell;


}

@property (strong, nonatomic) TakePhotoController * takephoto;

@end

@implementation MessageViewController

@synthesize pictureBtn;
@synthesize faceBtn;
@synthesize chatBar;
@synthesize chatInput;
@synthesize sendButtom;
@synthesize sayButtom;
@synthesize mp3RecordView;
@synthesize switchButtom;
@synthesize rightInfoBtn;

@synthesize chatPhoto;
@synthesize cameraImage;

@synthesize menuPublic;

@synthesize sessionId;
@synthesize session;
@synthesize sessInfo;


- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(chatRecvMessage:) name:DE.msgBroadcastName object:nil];
         [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(contactMessage:) name:CONTACT_CHANGE_BROADCAST object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:)
                                                     name:UIKeyboardWillShowNotification object:nil];
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:)
                                                     name:UIKeyboardWillHideNotification object:nil];
        
        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshMsgList:) name:PUBLIC_ATTENTION_BROADCAST object:nil];
    }
    return self;
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:YES];
//    [self scrollToBottomAnimated:NO];

}




- (void)refreshMsgList:(NSNotification *)notification{
    NSLog(@"刷新聊天界面");
    msgList= [MessageDao queryMessageBySessionId:session.sess_id];
    [_messageTableview reloadData];
    [self scrollToBottomAnimated:YES];
    
}
- (void)chatRecvMessage:(NSNotification *)notification{
    
    msgList= [MessageDao queryMessageBySessionId:session.sess_id];
    [_messageTableview reloadData];
    [self scrollToBottomAnimated:YES];
}
- (void)contactMessage:(NSNotification *)notification{
    
    NSDictionary* msg = [notification object];
    NSString * pass_sessionId = [msg objectForKey:@"sessionID"];
    NSString * pass_businessId = [msg objectForKey:@"businessId"];
    if ([@"updateGrpName" isEqualToString:[msg objectForKey:@"businessId"]]) {
        
        if ([session.sess_id isEqualToString:pass_sessionId]) {
            session = [MessageSessionDao queryMsgSessionById:pass_sessionId];
            
            self.lableTitle.text=session.title;
        }
    }
    // 解散群组或者删除好友，则要关闭当前界面
    else if(([@"dropGrp" isEqualToString:pass_businessId]||[@"endFriendship" isEqualToString:pass_businessId])
            &&[session.sess_id isEqualToString:pass_sessionId]){
        
        [self.navigationController popViewControllerAnimated:YES];
    }

}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    heightForCell = [[NSMutableDictionary alloc] initWithCapacity:20];
    if (session) {
        sessionId = session.sess_id;
    }else {
        //需要创建session
        NSString* messtype =@"";
        NSString *sessionType =@"";

        if(!sessionId){
            dbrecordDBPKID = [sessInfo objectForKey:@"record_DB_ID"];
            sessionType = [sessInfo objectForKey:@"sessionType"];
            messtype  =[sessInfo objectForKey:@"messtype"];
            dbrecordID = [sessInfo objectForKey:@"recordID"];
            sessionId = [NSString stringWithFormat:@"%@_%@",sessionType,dbrecordID];
        }
        // 根据传过来的或者新成功生成的sessoionId去获取session
        session = [MessageSessionDao queryMsgSessionById:sessionId];
        // 如果从数据库中未获取到改聊天的session，则生成一个
        if (!session) {
            if (dbrecordDBPKID && dbrecordID) {
                NSString* sessionName = @"";
                NSString* sessionPic = @"";
                NSString* isremind = @"1";
                // 从contacts表里面获取数据
                if([@"0" isEqualToString:messtype]||[@"1" isEqualToString:messtype]||[@"2" isEqualToString:messtype]){
                    
                    Contact *record = [ContactDao getContactByPKId:dbrecordDBPKID];
                    sessionPic = record.mHEAD_IMG;
                    sessionName = record.mNAME;
                    if ([@"usergrp" containString:record.mID] || [@"0" isEqualToString:record.mIS_ACTIVATED]) {
                        NSLog(@"设置了消息免打扰。。。。。。");
                        isremind=@"0";
                    }
                }else {
                    //TODO 公众号
                    PublicAccount *record = [PublicAccountDao queryForId:dbrecordDBPKID];
                    sessionPic = record.headImg;
                    sessionName = record.appName;
                }
                session = [[MessageSession alloc] initWithData:sessionId sesType:sessionType oppositeId:dbrecordID title:sessionName text:@"" sessionPic:sessionPic isremind:isremind updatime:[NSDate date] otherInfo:nil];
                [MessageSessionDao insertMessageSeesion2DB:session];
            }
        }
    }
    
    if(!session){
        
        return;
    }
    
    
    [self addTitleBarWithBackBtn:session.title needReturn:YES];
    
    tableHeight =self.view.frame.size.height-CHATBAR_HEIGHT-TITLE_BAR_HEGIHT-(YNEW);

    _messageTableview = [[UITableView alloc] initWithFrame:CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, tableHeight) style:UITableViewStylePlain];
    
    _messageTableview.separatorStyle = NO;
    _messageTableview.tableHeaderView.backgroundColor = [UIColor whiteColor];

    _messageTableview.delegate = self;
    _messageTableview.dataSource = self;
    _messageTableview.backgroundColor = [UIColor colorWithRed:239/255.0f green:239/255.0f blue:239/255.0f alpha:0.9];
    
    //防止iOS8下面的内存警告
    _messageTableview.rowHeight = 44.0f;
    
    UILongPressGestureRecognizer *gestureLongPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(didLongClickRowAtIndexPath:)];
    gestureLongPress.minimumPressDuration =1;
    [_messageTableview addGestureRecognizer:gestureLongPress];

    [self.view addSubview:_messageTableview];
    
    rightInfoBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    rightInfoBtn.frame = CGRectMake(SCREEN_WIDTH-50, (YNEW)+3, 44.0f, 38.0f);
    [rightInfoBtn addTarget:self action:@selector(messageShowRightView:) forControlEvents:UIControlEventTouchDown];
    [self.titlebar addSubview:rightInfoBtn];
    UIImageView * btnBackgroundImg = [[UIImageView alloc] initWithFrame:CGRectMake(SCREEN_WIDTH-50, (YNEW)+6, 25.0f, 24.0f)];
    btnBackgroundImg.image = [UIImage imageNamed:@"contacts_info_icon"];
    
    [self.titlebar addSubview:btnBackgroundImg];
    
    [self createChatView];
    
    if ([session.sess_id containString:@"PUB"]) {
        PublicAccount *pa = [PublicAccountDao queryForId:dbrecordDBPKID];
        //该公众号能够聊天，则加载底部菜单
        if ([@"1" isEqualToString:pa.disableChat]) {
            self.chatBar.hidden=YES;
            tableHeight =self.view.frame.size.height-TITLE_BAR_HEGIHT-YNEW;
            _messageTableview.frame =CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, tableHeight);
        }else{
            menuPublic = [[PublicBottmMenuView alloc] initWithFrame:CGRectMake(CHART_COMM_WIDTH+2*CHATBAR_COMM_GAP, self.view.frame.size.height-CHART_COMM_HEIGHT-CHATBAR_COMM_GAP, SCREEN_WIDTH-CHART_COMM_WIDTH-3*CHATBAR_COMM_GAP, CHART_COMM_HEIGHT)];
            [self.view addSubview:menuPublic];
            
            __weak MessageViewController *ctl = self;
            menuPublic.delegate = ctl;
            [menuPublic getBottonMenuData:session.oppositeId];
        }
    }
    // 系统消息下面无对话框
    else if([@"cmd_system" isEqualToString:session.sess_id]){
        rightInfoBtn.hidden = YES;
        btnBackgroundImg.hidden = YES;
        self.chatBar.hidden=YES;
        tableHeight =self.view.frame.size.height-TITLE_BAR_HEGIHT-YNEW;
        _messageTableview.frame =CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, tableHeight);
        
    }
    //如果该条会话由陌生人发起则去网络获取联系人数据
    if ([@"1" isEqualToString:[session getValue:@"stranger" ]]) {
        //先查询陌生信息
        rightInfoBtn.hidden = YES;
        //查询陌生公众号
        if ([session.sess_id containString:@"PUB"]) {
            [self queryStrangerPublic:session.oppositeId];
        }
        //查询陌生人
        else{
            [self queryStrangerFriend:session.oppositeId];
        }
            
    }
    
    msgList= [MessageDao queryMessageBySessionId:sessionId];
    recoder = [[MessageAudioRecoder alloc] init];
    if (_refreshHeaderView == nil) {
        EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - _messageTableview.bounds.size.height, self.view.frame.size.width, _messageTableview.bounds.size.height)];
        view.delegate = self;
        [_messageTableview addSubview:view];
        _refreshHeaderView = view;
    }
    
    NSString *keyWordds =[KeyWordDao queryKeyBooksById:[NSString stringWithFormat:@"%@_%@",DE.userId,@"keyBookVersion"]];
    if (keyWordds && !strIsEmpty(keyWordds)) {
        NSString *des = [ServerEngine decryptDES:keyWordds key:@"12345678"];
        kAppDelegate.keyWordList = [des objectFromJSONString];
    }else{
        [DE serverCall:@"queryKewordsList" params:[[NSDictionary alloc] init] callback:nil];
    }
    [_refreshHeaderView refreshLastUpdatedDate];
   
    [_messageTableview setContentOffset:CGPointMake(CGFLOAT_MAX, CGFLOAT_MAX)];

}


-(void)queryStrangerFriend:(NSString*)strangerId{
    [MBProgressHUD showHUDAddedTo:self.view prompt:@"正在获取该陌生人信息..." animated:YES];
    [DE serverCall:@"queryUserInfo" params:@{@"query_user_id":strangerId} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (success && [data objectForKey:@"user"]) {
            rightInfoBtn.hidden=NO;
            // 如果找不到陌生人机构，则创建一个
            if (![ContactDao getContactByPKId:[NSString stringWithFormat:@"stranger_%@",DE.userId]]) {
                [ContactDao insertStrangerOrg];
            }
            [ContactDao insertStrangerContactFromNet:[data objectForKey:@"user"]];
            // 更新当前session
            
            NSDictionary *contactInfo = [data objectForKey:@"user"];
            session.title =[contactInfo objectForKey:@"userName"];
            session.sessionPic =[contactInfo objectForKey:@"headImg"];
            [session putValue:@"0" key:@"stranger"];
            [MessageSessionDao updateMessageSession:session];
            kAppDelegate.needRefrsh = YES;
            self.lableTitle.text = [contactInfo objectForKey:@"userName"];
            [[NSNotificationCenter defaultCenter] postNotificationName:CONTACT_CHANGE_BROADCAST object:nil];
         }else{
             UIAlertView *aler = [[UIAlertView alloc] initWithTitle:@"提示" message:@"未获取到该陌生人信息！" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
            [aler show];
        }
    }];
}


-(void)queryStrangerPublic:(NSString*)strangerId{
    [MBProgressHUD showHUDAddedTo:self.view prompt:@"正在获取该陌生公众号信息..." animated:YES];
    [DE serverCall:@"getAppById" params:@{@"appId":strangerId} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (success && [data objectForKey:@"app"]) {
            rightInfoBtn.hidden=NO;
            NSDictionary *appInfo = [data objectForKey:@"app"];
            [PublicAccountDao insertPublicAccount:appInfo];
            //更新当前session
            session.title =[appInfo objectForKey:@"appName"];
            session.sessionPic =[appInfo objectForKey:@"headImg"];
            [session putValue:@"0" key:@"stranger"];
            [MessageSessionDao updateMessageSession:session];
            kAppDelegate.needRefrsh = YES;
            self.lableTitle.text = [appInfo objectForKey:@"appName"];
            [[NSNotificationCenter defaultCenter] postNotificationName:PUBLIC_ATTENTION_BROADCAST object:nil];
        }else{
            UIAlertView *aler = [[UIAlertView alloc] initWithTitle:@"提示" message:@"未获取到该陌生公众号信息！" delegate:self cancelButtonTitle:@"返回" otherButtonTitles:nil, nil];
            [aler show];
        }
    }];
}

#pragma mark - 弹出框代理

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    [self.navigationController popViewControllerAnimated:YES];
}


#pragma mark -
#pragma mark EGORefreshTableHeaderDelegate Methods
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
}
- (BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView*)view{
    return NO;
}
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
}
- (void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView*)view{
    [self reloadTableViewDataSource];
}
- (NSDate*)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView*)view{
    return [NSDate date];
}
- (void)reloadTableViewDataSource{
    
    int dbCount = [MessageDao queryMsgCountBySeesion:session.sess_id];
    long currsize = msgList?msgList.count : 0;
    bool isLocalhave = dbCount - currsize > 0;
    if (!isLocalhave) {
        Message *messagee;
        for (Message *msg in msgList) {
            if ([msg getValue:@"isSucceed"]) {
                if ([@"true" isEqualToString:[msg getValue:@"isSucceed"]]) {
                    messagee = msg;
                    break;
                }
            } else {
                messagee = msg;
                break;
            }
        }
        NSDate *date =messagee?(messagee.upate_time?messagee.upate_time:[messagee getValue:@"sendTime"]):nil;
        NSString *time = date?[date stringFromDateDB]:@"" ;
        NSDictionary * para =@{@"receiverId":session.oppositeId,@"senderId":DE.userId,
                               @"timestamp":time};
        [DE serverCall:@"queryHisMessage" params:para
              callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
                    if (success) {
                      NSArray * records = [data objectForKey:@"msg"];
                       if (records) {
                           if (records.count==0) {
                               [self showAlerHUD:@"已经没有更多历史消息了！"];
                           }
                           else{
                               for (NSDictionary *record in records) {
                                   [MessageSessionDao updataDBwithSQLiteStatement:record];
                               }
                               msgList= [MessageDao queryMessageBySessionId:session.sess_id];
                               [_messageTableview reloadData];
                            }
                       }
                   }else{
                      [self showAlerHUD:@"获取历史消息错误！"];
                   }
                  [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:_messageTableview];

        }];
    }

}

-(void)viewDidUnload
{
    [super viewDidUnload];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:DE.msgBroadcastName
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification
                                                  object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification
                                                  object:nil];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [msgList count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    Message *message = [msgList objectAtIndex:indexPath.row];
    Message *preMessage =nil;
    if (indexPath.row>0) {
        preMessage =[msgList objectAtIndex:indexPath.row-1];
    }
    
    if([message.mediaType isEqualToString:MEDIATYPE_TEXT] ||[message.mediaType isEqualToString:MEDIATYPE_AUDIO]
       ||[message.mediaType isEqualToString:MEDIATYPE_PICTURE]){
        if ([message isMine]) {
            static NSString * CellIdentifier = @"MessageSendCell";
            MessageSendCell* cell = (MessageSendCell*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
            if (!cell) {
                cell = [[MessageSendCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
              
                [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            }
            
            [cell setMsgCellValue:message preMessage:preMessage session:session];
            return cell;

        }else{
            static NSString * CellIdentifier = @"MessageReceiveCell";
            MessageReceiveCell* cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
            if (!cell) {
                cell = [[MessageReceiveCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
                [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
            }
            
            [cell setMsgCellValue:message preMessage:preMessage session:session];
            return cell;

        }
    }
    
    else if([MEDIATYPE_NEWS isEqualToString:message.mediaType]){
        
        NSDictionary *allmap =[message getValue:@"news"];
        if (allmap) {
            NSArray * artlist = [allmap objectForKey:@"Articles"];
            //多图文
            if (artlist && [artlist count]>1) {
                
                static NSString * CellIdentifier = @"MultipleNewsCell";
                MultipleNewsCell* cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
                if (!cell) {
                    cell = [[MultipleNewsCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
                    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
                }
                
                [cell setMsgCellValue:message publicId:session.oppositeId];
                return cell;
                
            }else{
                
                static NSString * CellIdentifier = @"SingleNewsCell";
                SingleNewsCell* cell = [tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
                if (!cell) {
                    cell = [[SingleNewsCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
                    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
                }
                
                [cell setMsgCellValue:message publicId:session.oppositeId];
                return cell;
                
            }
        }
        
    }
    
    else if([MEDIATYPE_URL isEqualToString:message.mediaType]){
        static NSString * CellIdentifier = @"UrlCell";
        UrlCell* cell = (UrlCell*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
        if (!cell) {
            cell = [[UrlCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        [cell setMsgCellValue:message publicId:session.oppositeId];
        
        return cell;

    }
    else if([MEDIATYPE_SIGN isEqualToString:message.mediaType]){
        static NSString * CellIdentifier = @"SignCell";
        SignCell* cell = (SignCell*)[tableView dequeueReusableHeaderFooterViewWithIdentifier:CellIdentifier];
        if (!cell) {
            cell = [[SignCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
            [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
        }
        [cell setMsgCellValue:message publicId:session.oppositeId];
        return cell;
    }
    
    return nil;
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{

    return [self cellForEachHeight:indexPath.row];

}

#pragma mark - Table view Helper
- (CGFloat)cellForEachHeight:(NSInteger)index
{

    Message *message = [msgList objectAtIndex:index];
    Message *preMessage =nil;
    
    CGFloat height = [[heightForCell objectForKey:message.mID] floatValue];
    if (height != 0){
        return height;
    }
    
    CGFloat curHeight = 0;

    if (index>0) {
        preMessage =[msgList objectAtIndex:index-1];
    }
    BOOL isShwoTimeLable = NO;
    if (preMessage) {
        NSTimeInterval secondsBetweenDates= [message.upate_time timeIntervalSinceDate:preMessage.upate_time];
        isShwoTimeLable = secondsBetweenDates>=30.0f;
    }else{
        isShwoTimeLable =YES;
    }
    
    if([message.mediaType isEqualToString:MEDIATYPE_TEXT] ||[message.mediaType isEqualToString:MEDIATYPE_AUDIO]
       ||[message.mediaType isEqualToString:MEDIATYPE_PICTURE]){
        NSString *contentText = @"";
        if ([MEDIATYPE_PICTURE isEqualToString:message.mediaType]) {
            return PICTURE_CELL_HEIGTH +  (isShwoTimeLable? TIME_LABEL_HEGIHT+CELL_COM_GAP*3:CELL_COM_GAP*2);
        }
        else if([MEDIATYPE_AUDIO isEqualToString:message.mediaType]){
            contentText = @"X秒";
        }else if([MEDIATYPE_TEXT isEqualToString:message.mediaType]){
            contentText = message.text;
        }
         CGFloat height = 0;
        M80AttributedLabel *label = [[M80AttributedLabel alloc]initWithFrame:CGRectZero];
        [BaseTableCell addCoreTextMessage:contentText label:label];
        CGSize size = [label sizeThatFits:CGSizeMake(MAX_CONTENT_WIDTH, CGFLOAT_MAX)];
        height = size.height;
        curHeight = height +  (isShwoTimeLable? (TIME_LABEL_HEGIHT)+CELL_COM_GAP*3:CELL_COM_GAP*2) +TEXT_BUBBLE_GAP*2;
        

     }
    
    else if([MEDIATYPE_NEWS isEqualToString:message.mediaType]){
        NSDictionary *allmap =[message getValue:@"news"];
        if (allmap) {
            NSArray * artlist = [allmap objectForKey:@"Articles"];
            //多图文
            if (artlist && [artlist count]>1) {
                curHeight= BIG_IMAGE_HEIGHT +2*NEW_CELL_COM_GAP +(artlist.count-1) *CELL_OTHER_CELL;
            }else{
                curHeight= SINGLE_NEWS_CELL;
            }
        }
    }
    else if([MEDIATYPE_URL isEqualToString:message.mediaType]){
        NSDictionary * dataMap =[message getValue:@"url"];
        CGSize contentSize = [[dataMap objectForKey:@"title"] sizeWithFont:[UIFont systemFontOfSize:14] constrainedToSize:CGSizeMake(SCREEN_WIDTH-4*NEW_CELL_COM_GAP, CGFLOAT_MAX)lineBreakMode:NSLineBreakByWordWrapping];
        curHeight= contentSize.height +6*NEW_CELL_COM_GAP +TIME_AUTHOR_LOOK_HEIGHT*2;
        
    } else if([MEDIATYPE_SIGN isEqualToString:message.mediaType]){
        CGSize contentSize = [message.text sizeWithFont:[UIFont systemFontOfSize:FONT_TITLE_SIZE_SIGN] constrainedToSize:CGSizeMake(SCREEN_WIDTH-5*NEW_CELL_COM_GAP-SIGN_BTN_WIDTH, CGFLOAT_MAX)lineBreakMode:NSLineBreakByWordWrapping];
        curHeight = TIME_SING_HEIGHT +(6*NEW_CELL_COM_GAP) + contentSize.height;
        
    }else{
        curHeight =  SINGLE_NEWS_CELL;
     }
    [heightForCell setObject:@(curHeight) forKey:message.mID];


    return curHeight;
}

//指定标题的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.01;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    return 0.01;
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    Message *msg = [msgList objectAtIndex:indexPath.row];
    NSLog(@"--------%@ =",msg.otherInfo);
    NSLog(@"--------%@ =",msg.text);

    if ([MEDIATYPE_AUDIO isEqualToString:msg.mediaType]) {
        
        NSString *loaclPath = [msg getValue:@"file"];
        NSFileManager *fileManager = [NSFileManager defaultManager];
        
        //如果存在本地文件
        if([fileManager fileExistsAtPath:loaclPath]) {
            NSURL *url = [NSURL fileURLWithPath:loaclPath];
            if (!recoder) {
                recoder = [[MessageAudioRecoder alloc] init];
            }
            [recoder playRecordSoundWithURL:url];
        }
        else {
            
            NSString *textUrl = [NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,msg.text];
            NSString *textPath =[StorageEngine readloadNetFile:textUrl];
             //如果下载过
             if([fileManager fileExistsAtPath:textPath]) {
                 NSURL *url = [NSURL fileURLWithPath:textPath];
                 if (!recoder) {
                     recoder = [[MessageAudioRecoder alloc] init];
                 }
                 [recoder playRecordSoundWithURL:url];
             }else{
                 //如果下载成功
                 if([StorageEngine downloadNetFile:textUrl]){
                     NSURL *url = [NSURL fileURLWithPath:textPath];
                     if (!recoder) {
                         recoder = [[MessageAudioRecoder alloc] init];
                     }
                     [recoder playRecordSoundWithURL:url];
                 }
                 
             }
            
        }

    }else if([MEDIATYPE_PICTURE isEqualToString:msg.mediaType]){

        ImageShowerController * imgCont = [[ImageShowerController alloc]init];
        if ([msg isMine]) {
            if ([msg getValue:@"file"]) {
                imgCont.filePath =[msg getValue:@"file"];
            }else{
                imgCont.filePath =[msg.text hasPrefix:@"http"]?msg.text:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,msg.text];
            }
        }else{
            NSString *url =[msg getValue:@"url"];
            imgCont.filePath = [url hasPrefix:@"http"]?url:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,url];
        }
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:imgCont animated:NO];


    }
    //单新闻/签到跳转
    else if([MEDIATYPE_NEWS isEqualToString:msg.mediaType] ||[MEDIATYPE_URL isEqualToString:msg.mediaType]){
        WebViewController * detail = [[WebViewController alloc] init];

        if([MEDIATYPE_URL isEqualToString:msg.mediaType]){
            NSDictionary * dataMap =[msg getValue:@"url"];
            NSString *urlStr =[dataMap objectForKey:@"url" ];
            detail.webUrl = [urlStr hasPrefix:@"http"]?urlStr:[NSString stringWithFormat:@"%@%@",DE.fileEngineeUrl,urlStr];

        }else{
            NSDictionary * allmap =[msg getValue:@"news"];
            NSArray * artlist = [allmap objectForKey:@"Articles"];
            NSDictionary *clickData = [artlist objectAtIndex:0];
            detail.webUrl = [clickData objectForKey:@"Url" ];
        }
        detail.publicId = session.oppositeId;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:detail animated:NO];
    }else if([MEDIATYPE_SIGN isEqualToString:msg.mediaType]
             &&![@"1" isEqualToString:[msg getValue:@"signState"]]){
        
        [MBProgressHUD showHUDAddedTo:self.view prompt:@"正在签收..." animated:NO];
        [DE serverCall:@"signMass" params:@{@"massId":[msg getValue:@"insCode"]} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
            
            [MBProgressHUD hideAllHUDsForView:self.view animated:NO];
            if (success && data && [data objectForKey:@"result"]) {
                [MessageDao updataMessageAddOtherInfo:msg addInfo:@{@"signState":@"1"} time:[NSDate date]];
            }
        }];
        [_messageTableview reloadData];
    }
}

-(void)onButtonClick:(id)sneder messge:(Message* )msg{
        
    [DE serverCall:@"signMass" params:@{@"massId":[msg getValue:@"insCode"]} callback:^(BOOL success, int code, NSString *desc, NSDictionary *data, NSDictionary *params) {
        
        if (success && data && [data objectForKey:@"result"]) {
            [MessageDao updataMessageAddOtherInfo:msg addInfo:@{@"signState":@"1"} time:[NSDate date]];
        }
        [_messageTableview reloadData];
    }];
}

- (void)didLongClickRowAtIndexPath:(UILongPressGestureRecognizer *)gestureRecognizer
{
    CGPoint tmpPointTouch = [gestureRecognizer locationInView:self.messageTableview];
    if (gestureRecognizer.state ==UIGestureRecognizerStateBegan) {
        NSIndexPath *indexPath = [self.messageTableview indexPathForRowAtPoint:tmpPointTouch];
        if (indexPath == nil) {
            NSLog(@"not tableView");
        }else{
            Message *msg = [msgList objectAtIndex:[indexPath row]];
            // 如果是文字消息
            if([MEDIATYPE_TEXT isEqualToString:msg.mediaType]){
                
                if ([@"false" isEqualToString:[msg getValue:@"isSucceed"]]) {
                    NSString *text = msg.text;
                    [MessageDao deleteMessageById:msg.mID];
                    [self sendMesaage2Service:MEDIATYPE_TEXT text:text data:nil];
                }else{
                    
                    UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
                    pasteboard.string = msg.text;
                    
                    [self showAlerHUD:@"成功复制到剪贴板"];
                }
                
            }
            // 如果是多媒体消息
            else{
                if ([@"false" isEqualToString:[msg getValue:@"isSucceed"]]){
                    // 没有发送成功，则重新发送
                    // 该字段没有值，说明文件没有上传成功，还没有url，这个时候需要重新上传文件
                    if (msg.text.length==0) {
                        // 加入该msg的id是为了回调返回的时候能方便找出需要操作的是界面上的哪个message。
                        // 第一次上传文件时候在message生成之后也传入了这个值
                        //msg putValue("waitSendId", msg.ID);
                        [msg putValue:msg.mID key:@"waitSendId"];
                        NSDictionary *otherinfo =[msg getOtherInfoContentMap];
                        [UploadFile uploadFileWithFilePath:[msg getValue:@"file"] servicePath:@"message" params:otherinfo calback:^(BOOL success, int code, NSString *desc, NSDictionary *netdata, NSDictionary *params) {
                            
                            [self dealAfterUploadMediaFile:otherinfo meidaUrl:netdata?[netdata objectForKey:@"URL"]:nil success:success];
                            
                        }];
                    }
                    else{
                        // 直接移除已经是正式的message，重现发送一条（类似文本消息)
                        NSString *text = msg.text;
                        NSDictionary *otherinfo =[msg getOtherInfoContentMap];
                        NSMutableDictionary *map = [[NSMutableDictionary alloc] init];
                        [map setObject:@"file" forKey:[otherinfo objectForKey:@"file"]];
                        [map setObject:@"filename" forKey:[otherinfo objectForKey:@"filename"]];
                        [map setObject:@"length" forKey:msg.length];

                        [MessageDao deleteMessageById:msg.mID];
                        [self sendMesaage2Service:msg.mediaType text:text data:map];
                    }
                }
            }
            
        }
    }
}


-(void)messageShowRightView:(id)sender
{
   //20150718要核实下讨论组和群的区别是什么？？
    //session.sess_id 如何区分
    // NSLog(@"群资料");
   // {
        //测试用的：20150715
        /*GroupDetailController *group = [[GroupDetailController alloc]init];
        group.groupid = session.oppositeId;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:group animated:NO];*/
        //20150717群资料信息
      //  GroupInfoViewController *group = [[GroupInfoViewController alloc]init];
      //   group.groupid = session.oppositeId;
      //   [kAppDelegate.iCSDrawerController.navigationController pushViewController:group animated:NO];
        //return;
    //}
    
    NSLog(@"session.sess_id:%@",session.sess_id);
    // 说明为公众号
    if ([session.sess_id containString:@"PUB"]) {
        PublicInforDetailViewController * public = [[PublicInforDetailViewController alloc] init];
        public.publicaccount = [PublicAccountDao queryForId:session.oppositeId];
        public.sessionId=session.sess_id;
        public.publicType = session.title;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:public animated:NO];
    }
    // 说明为自建的讨论组p2g_usergrp_1410399958236263_1234
    else if ([session.sess_id containString:@"usergrp"]) {
        
        NSLog(@"$$$$$$$$$$$$$$$$$");
        GroupDetailController *group = [[GroupDetailController alloc]init];
        group.groupid = session.oppositeId;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:group animated:NO];
    }
    // 个体联系人（或者固定群组和虚拟群组）
    else  {
       // if ([contact.mTYPE isEqualToString:@"O"])
        NSLog(@"联系人资料");
        NSString *iid = @"";
        if (dbrecordDBPKID &&dbrecordDBPKID.length>0) {
            iid =dbrecordDBPKID;
        }else if (dbrecordID &&dbrecordID.length>0) {
            iid =dbrecordID;
        }else{
            iid =session.oppositeId;
        }
       Contact *contact = [ContactDao getContactByPKId:iid];
        if (!contact) {
            contact = [ContactDao getContactById:iid];
            if (!contact) {
                [self showAlerHUD:@"未获取到更多详细信息！"];
            }
        }
         NSLog(@"xxxxxxxxxxxxxxxxx:iid %@",iid);
        NSLog(@"xxxxxxxxxxxxxxxxx:pkidd %@",contact.mPK_ID);
        //需要继续核实这个ID判断是否还有问题(讨论组和群组走这个流程)
        if ([contact.mTYPE isEqualToString:@"O"]) //群组，调用群资料
        {
            GroupInfoViewController *group = [[GroupInfoViewController alloc]init];
            group.groupid = session.oppositeId;
            group.grouptype = TYPE_GROUP_PUTONG;
            [kAppDelegate.iCSDrawerController.navigationController pushViewController:group animated:NO];
        }
        else  //个人资料
        {
            ContactDetailController *person = [[ContactDetailController alloc]init];
            person.contactId = iid;
            person.TypeContact = @"1";
            [kAppDelegate.iCSDrawerController.navigationController pushViewController:person animated:NO];
        }
    }
}


-(void)scrollToBottomAnimated:(BOOL)animated {
    
    if(_messageTableview.contentSize.height>_messageTableview.bounds.size.height)
        [_messageTableview setContentOffset:CGPointMake(0, _messageTableview.contentSize.height -_messageTableview.bounds.size.height) animated:YES];
}
- (void)createChatView{
    
    //输入框背景图片
    self.chatBar = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-CHATBAR_HEIGHT, SCREEN_WIDTH, CHATBAR_HEIGHT)];
    self.chatBar.userInteractionEnabled = YES;
    self.chatBar.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    self.chatBar.image = [UIImage imageNamed:@"message_chat_input_back.png"];
    [self.view addSubview:self.chatBar];
    
    
    /**基本输入框*/
    //输入方式切换按钮
    self.switchButtom = [UIButton buttonWithType:UIButtonTypeCustom];
    self.switchButtom.frame = CGRectMake(CHATBAR_COMM_GAP, CHATBAR_COMM_GAP, CHART_COMM_WIDTH, CHART_COMM_HEIGHT);
    
    [self.switchButtom setBackgroundImage:[UIImage imageNamed:[session.sess_id containString:@"PUB"]?
                                           @"mmfooter_listtotexticon_normal":@"chatting_setmode_keyboard_btn_normal"] forState:UIControlStateNormal];
    self.switchButtom.showsTouchWhenHighlighted = YES;
    [self.switchButtom addTarget:self action:@selector(switchButtomClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.chatBar addSubview:self.switchButtom];
    
    
    
    //文本输入
    self.chatInput = [[UITextView alloc] initWithFrame:CGRectMake(CHATBAR_COMM_GAP*2+CHART_COMM_WIDTH, CHATBAR_COMM_GAP, SCREEN_WIDTH-5*CHATBAR_COMM_GAP-CHART_COMM_WIDTH*3, CHART_COMM_HEIGHT)];
    self.chatInput.delegate = self;
    self.chatInput.scrollEnabled = YES; // not initially
    self.chatInput.font = [UIFont systemFontOfSize:CHATINPUT_FONT_SIZE];
    self.chatInput.dataDetectorTypes = UIDataDetectorTypeAll;
    self.chatInput.backgroundColor = [UIColor whiteColor];
    [self.chatBar addSubview:self.chatInput];
    
    //语音输入
    self.sayButtom = [[UIButton alloc] initWithFrame:CGRectMake(2*CHATBAR_COMM_GAP+CHART_COMM_WIDTH, CHATBAR_COMM_GAP, SCREEN_WIDTH-4*CHATBAR_COMM_GAP-2*CHART_COMM_WIDTH, CHART_COMM_HEIGHT)];
    UIImage *image = [UIImage imageNamed:@"btn_disable_normal.png"];
    image = [image stretchableImageWithLeftCapWidth:floorf(10) topCapHeight:floorf(10)];
    [self.sayButtom setBackgroundImage:image forState:UIControlStateNormal];
    [self.sayButtom setTitle:@"按住 说话" forState:UIControlStateNormal];
    self.sayButtom.showsTouchWhenHighlighted = YES;
    self.sayButtom.titleLabel.font = [UIFont systemFontOfSize:FONT_SIZE_SMALL];
    [self.chatBar addSubview:self.sayButtom];
    
    //表情按钮
    faceBtn = [[UIButton alloc] initWithFrame:CGRectMake(3*CHATBAR_COMM_GAP+CHART_COMM_WIDTH+self.chatInput.frame.size.width,CHATBAR_COMM_GAP,CHART_COMM_WIDTH, CHART_COMM_WIDTH) ];
    [faceBtn setBackgroundImage:[UIImage imageNamed:@"emji_normal"] forState:UIControlStateNormal];
    [faceBtn setBackgroundImage:[UIImage imageNamed:@"emji_normal"] forState:UIControlStateHighlighted];
    [self.faceBtn addTarget:self action:@selector(faceBtn:) forControlEvents:UIControlEventTouchDown];
    [self.chatBar addSubview:faceBtn];
    
    //发送图片按钮
    pictureBtn = [[UIButton alloc] initWithFrame:CGRectMake(4*CHATBAR_COMM_GAP+2*CHART_COMM_WIDTH+self.chatInput.frame.size.width,CHATBAR_COMM_GAP,CHART_COMM_WIDTH, CHART_COMM_WIDTH) ];
    [pictureBtn setBackgroundImage:[UIImage imageNamed:@"send_picture_btn_press"] forState:UIControlStateNormal];
    [pictureBtn setBackgroundImage:[UIImage imageNamed:@"send_picture_btn_normal"] forState:UIControlStateHighlighted];
    [self.pictureBtn addTarget:self action:@selector(pictureBtn:) forControlEvents:UIControlEventTouchDown];
    [self.chatBar addSubview:pictureBtn];
    
    //文字发送按钮
    self.sendButtom = [UIButton buttonWithType:UIButtonTypeCustom];
    self.sendButtom.titleLabel.font = [UIFont systemFontOfSize:FONT_SIZE_SMALL];
    
    [[UIImage imageNamed:@"blue_btn_normal"] stretchableImageWithLeftCapWidth:20 topCapHeight:20];

    [self.sendButtom setBackgroundImage:[[UIImage imageNamed:@"blue_btn_normal"] stretchableImageWithLeftCapWidth:20 topCapHeight:20] forState:UIControlStateNormal];
    [self.sendButtom setBackgroundImage:[[UIImage imageNamed:@"blue_btn_press"] stretchableImageWithLeftCapWidth:20 topCapHeight:20] forState:UIControlStateHighlighted];
    [self.sendButtom setTitle:@"发送" forState:UIControlStateNormal];
    [self.sendButtom setTitle:@"发送" forState:UIControlStateHighlighted];
    [self.sendButtom setTitleColor:RGBCOLOR(211, 231, 254) forState:UIControlStateNormal];
    [self.sendButtom setTitleColor:RGBCOLOR(211, 231, 254) forState:UIControlStateHighlighted];
    [self.sendButtom addTarget:self action:@selector(sendTextMessage:) forControlEvents:UIControlEventTouchUpInside];
    self.sendButtom.frame = CGRectMake(4*CHATBAR_COMM_GAP+2*CHART_COMM_WIDTH+self.chatInput.frame.size.width,CHATBAR_COMM_GAP,CHART_COMM_WIDTH, CHART_COMM_WIDTH);
    self.sendButtom.autoresizingMask = UIViewAutoresizingFlexibleTopMargin;
    [self.chatBar addSubview:self.sendButtom];
  

    self.pictureBtn.hidden = NO;
    self.faceBtn.hidden = NO;
    self.chatInput.hidden = NO;
    self.sayButtom.hidden=YES;
    self.sendButtom.hidden = YES;

    /*表情选择框*/
    self.faceView = [[ZBMessageManagerFaceView alloc]initWithFrame:CGRectMake(0.0f,self.view.frame.size.height-CHATBAR_ICON_HEIGHT, SCREEN_WIDTH, CHATBAR_ICON_HEIGHT)];
    self.faceView.delegate = self;
    [self.view addSubview:self.faceView];
    self.faceView.hidden=YES;
    
    
    /*语音输入提示框*/
    mp3RecordView = [[MessageAudioCSUView alloc] initWithFrame:CGRectMake(self.view.frame.size.width/4, self.view.frame.size.height/3, self.view.frame.size.width/2, self.view.frame.size.height/4)];
    [mp3RecordView setSayButtomAction:self.sayButtom];
    mp3RecordView.delegate = self;
    [self.view addSubview:self.mp3RecordView];
    self.mp3RecordView.hidden = YES;
    
}


//在按钮内抬起 --发送录音
-(void)onRecordComplete:(NSURL*)localUrl recoder:(int)time{
    
    if (time<1) {
        return;
    }
    
    NSString * filename = [localUrl lastPathComponent];//stringByReplacingOccurrencesOfString:@".aac" withString:@""];
    NSString *filePath = [localUrl path];
    NSString *length = [NSString stringWithFormat:@"%i",time];
    NSMutableDictionary * msgMap =[[NSMutableDictionary alloc] initWithCapacity:5];
    [msgMap setObject:filePath forKey:@"file"];
    [msgMap setObject:filename forKey:@"filename"];
    [msgMap setObject:length forKey:@"length"];
    //生成一个临时显示的message
    NSString *waitSendId = [self generateMediaMessageForUI:msgMap data:MEDIATYPE_AUDIO];
    [msgMap setObject:waitSendId forKey:@"waitSendId"];    
    
    [UploadFile uploadFileWithFilePath:filePath servicePath:@"message" params:msgMap calback:^(BOOL success, int code, NSString *desc, NSDictionary *netdata, NSDictionary *params) {
        [self dealAfterUploadMediaFile:msgMap meidaUrl:netdata?[netdata objectForKey:@"URL"]:nil success:success];

    }];
    

}

-(void)dealAfterUploadMediaFile:(NSDictionary*)msgMap meidaUrl:(NSString*)mediaUrl success:(BOOL)isSuccess{
 
  
    NSString *waitSendId = [msgMap objectForKey:@"waitSendId"];
    Message *waitMesg = [MessageDao queryMsgByID:waitSendId];
    if (isSuccess) {
        // 如果上传成功则移除暂时做为界面显示的Message
        waitMesg = [MessageDao queryMsgByID:waitSendId];
        [MessageDao deleteMessageById:waitSendId];
        [self sendMesaage2Service:waitMesg.mediaType text:mediaUrl data:[[NSMutableDictionary alloc] initWithDictionary:msgMap]];
        
    }else{
        // 如果失败则更改暂时用于界面显示的Message的状态，同时时间变成最后一次重新发送的时间
        [MessageDao updataMessageAddOtherInfo:waitMesg addInfo:@{@"isSucceed":@"false"} time:[NSDate date]];
        [self refreshList];
        return;
    }
}

-(void)pictureBtn:(id)sender
{
    _takephoto = [TakePhotoController new];
    _takephoto.type = TakePhotoFromPhotoLibrary;
    _takephoto.isEdit = YES;
    __weak MessageViewController *ctl = self;
    _takephoto.blockComplete = ^(UIImage * image,NSDictionary*fileMap){
        NSMutableDictionary *map = [[NSMutableDictionary alloc]initWithDictionary:fileMap];
        //生成一个临时显示的message
        NSString* waitSendid = [ctl generateMediaMessageForUI:map data:MEDIATYPE_PICTURE];
        [map setObject:waitSendid forKey:@"waitSendId"];
        [UploadFile uploadFileWithFilePath:[fileMap objectForKey:@"file"] servicePath:@"HEAD_IMG" params:map calback:^(BOOL success, int code, NSString *desc, NSDictionary *netdata, NSDictionary *params) {
            [ctl dealAfterUploadMediaFile:map meidaUrl:netdata?[netdata objectForKey:@"URL"]:nil success:success];
        }];
    };
    
    [_takephoto startTakePhotoFromViewControl:self];

}
-(void)sendTextMessage:(id)sender{
    if(chatInput.text.length==0){
        
        [self showAlerHUD:@"不能发送空消息！"];
        return;
    }
    [self sendMesaage2Service:@"text" text:chatInput.text data:nil];
}

-(void)faceBtn:(id)sender
{
    /*NSLog(@"cccccccccccc faceBtn");
    [self.chatInput resignFirstResponder];
    if (self.faceView.isHidden)
    {
        self.faceView.hidden = NO;
        NSLog(@"11111111111111");
       tableHeight =self.view.frame.size.height-CHATBAR_HEIGHT-TITLE_BAR_HEGIHT-(YNEW);
        CGFloat height = self.view.frame.size.height-CHATBAR_HEIGHT-TITLE_BAR_HEGIHT-YNEW-CHATBAR_ICON_HEIGHT;
        NSLog(@"高度为：%d",tableHeight-CHATBAR_ICON_HEIGHT);
        //_messageTableview.frame 会报错
       // float _x = NAN;
       // if (!isnan(_x)) {
        
            NSLog(@"NAN NAN NAN NAN NAN NAN NAN NAN");
            //_messageTableview.frame = CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, 294);
            _messageTableview.frame = CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, tableHeight);
            //此处使用tableHeight不报错，使用 CGFloat 会报错
       // }
       self.chatBar.frame = CGRectMake(0, self.view.frame.size.height-CHATBAR_ICON_HEIGHT-CHATBAR_HEIGHT, SCREEN_WIDTH, CHATBAR_HEIGHT);
        [self.view bringSubviewToFront:self.faceView];
        [self scrollToBottomAnimated:YES];
    }else{
        self.faceView.hidden=YES;
         NSLog(@"XXXXXXXXXXXXXXX");
        _messageTableview.frame = CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, tableHeight);
        self.chatBar.frame = CGRectMake(0, self.view.frame.size.height-CHATBAR_HEIGHT, SCREEN_WIDTH, CHATBAR_HEIGHT);
        [self scrollToBottomAnimated:YES];

    }*/
    [self.chatInput resignFirstResponder];
    if (self.faceView.isHidden)
    {
        self.faceView.hidden = NO;
        _messageTableview.frame = CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, tableHeight-CHATBAR_ICON_HEIGHT);
        self.chatBar.frame = CGRectMake(0, self.view.frame.size.height-CHATBAR_ICON_HEIGHT-CHATBAR_HEIGHT, SCREEN_WIDTH, CHATBAR_HEIGHT);
        [self.view bringSubviewToFront:self.faceView];
        [self scrollToBottomAnimated:YES];
    }else{
        self.faceView.hidden=YES;
        _messageTableview.frame = CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, tableHeight);
        self.chatBar.frame = CGRectMake(0, self.view.frame.size.height-CHATBAR_HEIGHT, SCREEN_WIDTH, CHATBAR_HEIGHT);
        [self scrollToBottomAnimated:YES];
        
    }
}

#pragma mark - ZBMessageFaceViewDelegate

- (void)sendTheFaceStr:(NSString *)faceStr isDelete:(BOOL)dele
{
    if (!dele) {
        self.chatInput.text = [self.chatInput.text stringByAppendingString:faceStr];
    }else{
        if (self.chatInput.text.length>0) {
            self.chatInput.text = [self.chatInput.text substringToIndex:self.chatInput.text.length-1];
         }
    }
    [self textViewDidChange:nil];
}

#pragma mark UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView {
    
    NSString *rightTrimmedText = [self.chatInput.text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    self.sendButtom.hidden =!rightTrimmedText.length > 0;
    self.pictureBtn.hidden =rightTrimmedText.length > 0;
    
}


-(void)switchButtomClicked:(id)sender
{
    if ([session.sess_id containString:@"PUB"]) {

        
        if (menuPublic.isHidden) {
            [self.switchButtom setBackgroundImage:[UIImage imageNamed:@"mmfooter_listtotexticon_normal"] forState:UIControlStateNormal];
            menuPublic.hidden=NO;
            menuPublic.popupTableView.hidden = YES;
            
        }else{
            [self.switchButtom setBackgroundImage:[UIImage imageNamed:@"mmfooter_texttolisticon_normal"] forState:UIControlStateNormal];
            menuPublic.hidden=YES;

        }
    }
    else{

        if (self.sayButtom.isHidden) {
            //如果当前的说话按钮没显示，说明为文字发送
            [self.switchButtom setBackgroundImage:[UIImage imageNamed:@"chatting_setmode_keyboard_btn_normal"] forState:UIControlStateNormal];
            [self.chatInput resignFirstResponder];
            self.sayButtom.hidden = NO;
            self.pictureBtn.hidden = NO;
            self.chatInput.hidden = YES;
            self.sendButtom.hidden = YES;
            self.faceBtn.hidden = YES;
        }else{
            
            [self.switchButtom setBackgroundImage:[UIImage imageNamed:@"chatting_setmode_voice_btn_normal"] forState:UIControlStateNormal];
            self.sayButtom.hidden = YES;
            self.sendButtom.hidden = YES;
            self.chatInput.hidden = NO;
            self.pictureBtn.hidden = NO;
            self.faceBtn.hidden = NO;
        }
    }
}


# pragma mark Keyboard Notifications

- (void)keyboardWillShow:(NSNotification *)notification {
    self.faceView.hidden=YES;
    NSDictionary *userInfo = [notification userInfo];
    NSValue *aValue = [userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardRect = [aValue CGRectValue];
    int height = keyboardRect.size.height;
    _messageTableview.frame = CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, tableHeight-height);
    self.chatBar.frame = CGRectMake(0, self.view.frame.size.height-CHATBAR_HEIGHT-height, SCREEN_WIDTH, CHATBAR_HEIGHT);
    [self scrollToBottomAnimated:YES];
 }

- (void)keyboardWillHide:(NSNotification *)notification {
    self.faceView.hidden=YES;
    _messageTableview.frame = CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH,tableHeight);
    self.chatBar.frame = CGRectMake(0, self.view.frame.size.height-CHATBAR_HEIGHT, SCREEN_WIDTH, CHATBAR_HEIGHT);
    [self scrollToBottomAnimated:YES];
    
}


#pragma mark generate media message

-(NSString*) generateMediaMessageForUI:(NSDictionary*)mesMap data:(NSString*)mediaType{
   
    
    NSMutableDictionary * messageContentMap = [[NSMutableDictionary alloc] initWithDictionary:mesMap];
    
    [messageContentMap setObject:@"wait" forKey:@"isSucceed"];
    
    NSMutableDictionary * messageMap = [[NSMutableDictionary alloc] initWithCapacity:10];

    [messageMap setObject:messageContentMap forKey:@"content"];
    int randon = (arc4random() % 100000000000) + 1;
    NSString *messageId = [NSString stringWithFormat:@"%@_%@_%@_%d",DE.userId,session.oppositeId,session.sessionType,randon];
    [messageMap setObject:messageId forKey:@"id"];
    [messageMap setObject:[[self getLastItemTime] stringFromDateDB] forKey:@"update_time"];

    [messageContentMap setObject:messageId forKey:@"id"];
    [messageContentMap setObject:DE.userId forKey:@"senderId"];
    [messageContentMap setObject:session.oppositeId forKey:@"receiverId"];
    [messageContentMap setObject:session.sessionType forKey:@"messageType"];
    [messageContentMap setObject:mediaType forKey:@"mediaType"];
    [messageContentMap setObject:messageId forKey:@"waitSendId"];
    [messageContentMap setObject:[[self getLastItemTime] stringFromDateDB] forKey:@"update_time"];

    if([MESSAGE_TYPE_P2G isEqualToString:session.sessionType]){
        [messageContentMap setObject:session.oppositeId forKey:@"groupId"];
    }
    
    [MessageSessionDao updataDBwithSQLiteStatement:messageMap];

    [self refreshList];
    return messageId;
}

#pragma mark send message

-(void) sendMesaage2Service:(NSString*)mediaType text:(NSString*)text data:(NSMutableDictionary*)data{
    
    if ([mediaType isEqualToString:MEDIATYPE_TEXT]) {
        if (kAppDelegate.keyWordList) {
            for (NSString* key in kAppDelegate.keyWordList) {
                if ([text containString:key]) {
                    [super colseKeyboard];
                    [self showAlerHUD:[NSString stringWithFormat:@"' %@ '为敏感词,请更改后再发送！",key]];
                    return;
                }
            }
            
        }else{
            NSString *keyWordds =[KeyWordDao queryKeyBooksById:[NSString stringWithFormat:@"%@_%@",DE.userId,@"keyBookVersion"]];
            if (keyWordds && !strIsEmpty(keyWordds)) {
                NSString *des = [ServerEngine decryptDES:keyWordds key:@"12345678"];
                 kAppDelegate.keyWordList = [des objectFromJSONString];
            }else{
                [DE serverCall:@"queryKewordsList" params:[[NSDictionary alloc] init] callback:nil];
            }
        }
    }
    
 
    if (!data) {
        data =[[NSMutableDictionary alloc] init];
    }
    
    NSMutableDictionary *msgMap = [[NSMutableDictionary alloc] init];
    
    [data setObject:@"wait" forKey:@"isSucceed"];
    
    int randon = (arc4random() % 100000000000) + 1;
    NSString *messageId = [NSString stringWithFormat:@"%@_%@_%@_%d",DE.userId,session.oppositeId,session.sessionType,randon];
    [msgMap setObject:messageId forKey:@"id"];
    
    [data setObject:DE.userId forKey:@"senderId"];
    [data setObject:messageId forKey:@"waitSendId"];
    [data setObject:session.oppositeId forKey:@"receiverId"];
    [data setObject:session.sessionType forKey:@"messageType"];
    [data setObject:mediaType forKey:@"mediaType"];
    [data setObject:text forKey:@"text"];
    [data setObject:[[self getLastItemTime] stringFromDateDB] forKey:@"update_time"];
    
    if([MESSAGE_TYPE_P2G isEqualToString:session.sessionType]){
        [data setObject:session.oppositeId forKey:@"groupId"];
    }
    
    [msgMap setObject:data forKey:@"content"];

    [DE sendMessage:msgMap callback:^(BOOL success, int code, NSString *desc, NSDictionary *netdata, NSDictionary *params)
    {
    
        NSString *waitMsgId =[params objectForKey:@"waitSendId"];
        Message *waitMsg = [MessageDao queryMsgByID:waitMsgId];

        if(success && netdata && [netdata objectForKey:@"result"]){
            
            NSDate *time = [[netdata objectForKey:@"sendTime"] dateFromString];
            NSDictionary *other = @{@"isSucceed":@"true"};
            [MessageDao updataMessageAddOtherInfo:waitMsg addInfo:other time:time];
            
            session.text=session.text=![MEDIATYPE_TEXT isEqualToString:waitMsg.mediaType]?@"{多媒体消息}":waitMsg.text;
            [MessageSessionDao updateMessageSession:session];
            
        }else{
            NSDictionary* info =@{@"isSucceed":@"false"};
            [MessageDao updataMessageAddOtherInfo:waitMsg addInfo:info time:[NSDate date]];
        }
        [self refreshList];
    
    }];
    self.chatInput.text=@"";
    [self textViewDidChange:nil];

    
}

-(void)handleSwipeFrom{
    
    [super hidesBottomBarWhenPushed];
    [self.chatInput resignFirstResponder];
    if (!self.faceView.isHidden)
    {
        self.faceView.hidden=YES;
        _messageTableview.frame = CGRectMake(0, TITLE_BAR_HEGIHT+(YNEW), SCREEN_WIDTH, tableHeight);
        self.chatBar.frame = CGRectMake(0, self.view.frame.size.height-CHATBAR_HEIGHT, SCREEN_WIDTH, CHATBAR_HEIGHT);
    }

}


-(NSDate*)getLastItemTime{
    
    NSDate * lastTime = nil;
    if(msgList && msgList.count>0){
        Message* lastMessage = [msgList objectAtIndex:msgList.count-1];
        lastTime = [[NSDate alloc] initWithTimeInterval:1 sinceDate:lastMessage.upate_time];
    }else{
        
        lastTime = [NSDate date];
    }
    
    return lastTime;
    
}

-(void)refreshList{
    
    msgList= [MessageDao queryMessageBySessionId:session.sess_id];
    [_messageTableview reloadData];
    [self scrollToBottomAnimated:YES];

    
}

-(void)onPublicBottomMenuInitComplete:(NSDictionary*) menuData{
    //TODO
}

-(void)onPublicMenuItemClick:(NSDictionary*) clickData{
    
    if ([@"click" isEqualToString:[clickData objectForKey:@"type" ]]) {
        
        NSDictionary *paraDict = @{@"eventType":@"CLICK",@"eventKey":[clickData objectForKey:@"key" ],@"senderId":DE.userId,
                                   @"publicId":session.oppositeId};
        [DE serverCall:@"sendEvent" params:paraDict callback:nil];
    }
    else if ([@"view" isEqualToString:[clickData objectForKey:@"type" ]]) {
        NSLog(@"DDADDDDDDDDDDDDDDDDDDDDD");
        WebViewController * detail = [[WebViewController alloc] init];
        detail.webUrl = [clickData objectForKey:@"url" ];
        detail.publicId= session.oppositeId;
        [kAppDelegate.iCSDrawerController.navigationController pushViewController:detail animated:NO];
        
    }
    
}

//返回上一级页面
- (void)btnBack {
    //设置空，防止消息返回造成的指针错误
    menuPublic.delegate = nil;
    session.badgeNumber=0;
    [MessageSessionDao updateMessageSession:session];
    kAppDelegate.needRefrsh = YES;
    [super btnBack];
}

@end
